package com.xhsj.user.hr.system.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xhsj.user.hr.process.processDefinition.query.MapQuery;
import com.xhsj.user.hr.system.entity.RoleMenu;
import com.xhsj.user.hr.system.entity.TbGlobalRole;
import com.xhsj.user.hr.system.entity.TbHrZhaopinDemandApplyPosition;
import com.xhsj.user.hr.system.entity.UserRole;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.mapper.TbHrZhaopinDemandApplyPositionMapper;
import com.xhsj.user.hr.system.vo.BatchAuthorizationVo;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author suxl
 * @since Aug 27, 2020 10:31:54 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbGlobalRole")
public class TbGlobalRoleService extends ServiceImpl<TbGlobalRoleMapper, TbGlobalRole> {
    @Autowired
    private TbGlobalRoleMapper dao;

    @Autowired
    private TbHrZhaopinDemandApplyPositionMapper tbHrZhaopinDemandApplyPositionMapper;

	/**
	 * 保存
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
//    @Override
    //@CacheEvict(cacheNames="TbGlobalRole", allEntries=true)
    public boolean saveRole(TbGlobalRole entity) throws Exception {

        this.saveOrUpdateRole(entity);
        // 保存角色菜单
        this.saveRoleMenu(entity,entity.getMenuIds());
        return true;
    }

    /**
     * 保存角色菜单
     * @author 苏小林
     * @date 2020/9/1 13:46
     * @param: sysRole
     * @param: menuList
     */
    void saveRoleMenu(TbGlobalRole sysRole, List<Long> menuIds) {
        // 删除角色菜单
        dao.deleteByRoleId(sysRole.getRoleId());
        List<RoleMenu> menuList = Lists.newArrayList();
        menuIds.forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(sysRole.getRoleId());
            roleMenu.setMenuId(menuId);
            menuList.add(roleMenu);
        });
        dao.saveRoleMenu(menuList);

    }

//    public void testSaveRoleMenu() {
//
//        int [] menuIds = new int[] {1293,1294,1302,1306,1307,1314,1353,1354,1355,1360,1367,1368,1374,1375,1376,1378,1379,1380,1382,1383,1384,1385,1386,1387,1388,1389,1400,1401,1402,1404,1408,1409,1410,1411,1413};
//        int [] roleIds = new int[] {2,4,5,117,126,129,130,132,133,134,135,136,137,138,139,140,141,142,143,144,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172};
//        for (int roleId : roleIds) {
//            List<RoleMenu> menuList = Lists.newArrayList();
//            for (int menuId : menuIds) {
//                RoleMenu roleMenu = new RoleMenu();
//                roleMenu.setRoleId(Long.parseLong(roleId+""));
//                roleMenu.setMenuId(Long.parseLong(menuId+""));
//                menuList.add(roleMenu);
//            }
//            dao.saveRoleMenu(menuList);
//        }
//
//        System.err.println("保存完");
//    }

    private void saveOrUpdateRole(TbGlobalRole entity) throws Exception {
        if (StringUtils.isBlank(entity.getRoleId())) {
            int count = dao.findRoleKeynameIsExit(entity.getRoleKeyname());
            if (count >= 1) {
                log.error("角色标识已经存在");
                throw new Exception("角色标识已经存在");
            }

            entity.setCreateDate(entity.getCreateDate()==null?new Date():entity.getCreateDate());
            entity.setUpdateDate(entity.getUpdateDate()==null?new Date():entity.getUpdateDate());
            entity.setUpdateBy(entity.getUpdateBy()==null?entity.getCreateBy():entity.getUpdateBy());
            entity.setDelFlag(0);
            int insert = dao.insert(entity);
            if (insert == 0) {
                log.error("新增影响行数为0");
                throw new Exception("新增影响行数为0");
            }
        } else {
            entity.setRoleKeyname(null);
            entity.setUpdateDate(new Date());
            entity.setUpdateBy(entity.getUpdateBy()==null?entity.getCreateBy():entity.getUpdateBy());
            entity.setCreateBy(null);
            int i = dao.updateById(entity);
            if (i == 0) {
                log.error("修改影响行数为0");
                throw new Exception("新增影响行数为0");
            }
        }
    }

    /**
	 * 通过id获取数据
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbGlobalRole getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbGlobalRole", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbGlobalRole> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        String roleName = StringUtils.getStringValue(data, "roleName");

//        TbGlobalRole entity = JSON.parseObject(JSON.toJSONString(data), TbGlobalRole.class);
        Page<TbGlobalRole> page = new Page(currentPage,pageSize);
        QueryWrapper<TbGlobalRole> wrapper = new QueryWrapper();
        wrapper.like("role_name",roleName);
        return dao.selectPage(page, wrapper);
    }


    /**
     * 角色列表
     * 入职时 预设角色
     * @author liuqinghua
     */
    public List<MapQuery> loadList() {
        return dao.loadList();
    }

    /**
     * 查询所有角色
     * @author 苏小林
     * @date 2020/9/1 14:09
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public List<MapQuery> findRoles() {
        return dao.findRoles();
    }

    /**
     * 删除角色和菜单
     * @author 苏小林
     * @date 2020/9/2 10:04
     * @param: id
     */
    public void delRoleAndMenu(Long id) {
        dao.delRoleAndMenu(id);
    }

    /**
     * 查询用户RoleKeyNames列表
     * @author 苏小林
     * @date 2020/9/10 17:32
     * @param: userId
     * @return: java.util.List<com.xhsj.user.hr.system.entity.UserRole>
     */
    public List<String> getUserRoleKeyNames(Long userId) {
        return dao.getUserRoleKeyNames(userId);
    }


    /**
     * 批量授权
     * @author 苏小林
     * @date 2020/12/7 10:56
     * @param: batchAuthorizationVo
     */
    public void batchAuthorization(BatchAuthorizationVo batchAuthorizationVo) {

        // 角色列表
        List<Long> roleIds = batchAuthorizationVo.getRoleIds();

        // 菜单列表
        List<Long> menuIds = batchAuthorizationVo.getMenuIds();


        List<RoleMenu> menuList = Lists.newArrayList();

        for (Long roleId : roleIds) {
            for (Long menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                menuList.add(roleMenu);
            }
        }

        dao.replaceRoleMenu(menuList);
    }

    public TbGlobalRole saveRoleByName(String name) throws Exception {

        String roleKeyName = StringUtils.toPinyin(name);
        QueryWrapper<TbGlobalRole> wrapper = new QueryWrapper();
        wrapper.eq("role_name",name);
        List<TbGlobalRole> tbGlobalRoles = dao.selectList(wrapper);
        if (!tbGlobalRoles.isEmpty() || tbGlobalRoles.size() > 0) {
            throw new Exception("角色名称已经存在！");
        }

        TbGlobalRole tbGlobalRole = new TbGlobalRole();
        tbGlobalRole.setRoleName(name);
        tbGlobalRole.setRoleKeyname(roleKeyName);
        tbGlobalRole.setStatus(0);
        List<Long> menuIds = Lists.newArrayList();
        String menus = "1293,1294,1353,1354,1355,1360,1367,1368,1374,1375,1378,1379,1380,1382,1383,1400,1401,1402,1409,1410,1411,1413,1422,1424,1425,1427,1436,1437,1438,1440";
        String[] split = menus.split(",");
        for (String s : split) {
            menuIds.add(Long.parseLong(s));
        }
        tbGlobalRole.setMenuIds(menuIds);
        this.saveRole(tbGlobalRole);

        return tbGlobalRole;
    }

    public long getSnowIdIfNameNotExist(String name) throws Exception {
        QueryWrapper<TbGlobalRole> wrapper = new QueryWrapper();
        wrapper.eq("role_name",name);
        Integer integer1 = dao.selectCount(wrapper);

        QueryWrapper<TbHrZhaopinDemandApplyPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        Integer integer = tbHrZhaopinDemandApplyPositionMapper.selectCount(queryWrapper);

        if (integer1 > 0 || integer > 0) {
            throw new Exception("名称已经存在！");
        }
        return IdGen.snowId();

    }
}
